﻿using Farming.Domain.DTO;
using Farming.Domain.Traceabilities;
using Farming.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient.DataClassification;
using Microsoft.Extensions.Configuration;
using Panda.DynamicWebApi;
using Panda.DynamicWebApi.Attributes;
using QRCoder;
using System;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Farming.Domain.CustomClass;

namespace Farming.Application
{
    [DynamicWebApi]
    [ApiExplorerSettings(GroupName = "v1")]
    [Authorize]

    public class TraceabilityService : IDynamicWebApi
    {
        private readonly Repository<TraceabilityIndex> _TraceabilityIndexRepository;
        private readonly Repository<HusbandryMessage> _HusbandryMessageRepository;
        private readonly IConfiguration configuration;
        private readonly IWebHostEnvironment host;
        private readonly Repository<HealthInformation> _healthInformationRepository;
        private readonly Repository<CustomActionModel> _customActionModelRepository;
        private readonly Repository<SlaughterInformation> _slaughterInformationRepository;
        private readonly Repository<SlaughterImages> _slaughterImagesRepository;
        private readonly Repository<HusbandryEnterprise> _husbandryEnterpriseRepository;
        private readonly Repository<HusbandryEnterpriseImages> _husbandryEnterpriseImagesRepository;
        private readonly Repository<DeepProcessing> _deepProcessingRepository;
        private readonly Repository<DeepProcessingImages> _deepProcessingImagesRepository;
        public TraceabilityService(Repository<TraceabilityIndex> traceabilityIndexRepository, IConfiguration configuration, IWebHostEnvironment host, Repository<HusbandryMessage> _HusbandryMessageRepository, Repository<HealthInformation> healthInformationRepository, Repository<CustomActionModel> customActionModelRepository, Repository<HusbandryEnterprise> husbandryEnterpriseRepository, Repository<HusbandryEnterpriseImages> husbandryEnterpriseImagesRepository, Repository<SlaughterInformation> slaughterInformationRepository, Repository<SlaughterImages> slaughterImagesRepository, Repository<DeepProcessing> deepProcessingRepository, Repository<DeepProcessingImages> deepProcessingImagesRepository)
        {
            _TraceabilityIndexRepository = traceabilityIndexRepository;
            this._HusbandryMessageRepository = _HusbandryMessageRepository;
            this.configuration = configuration;
            this.host = host;
            _healthInformationRepository = healthInformationRepository;
            _customActionModelRepository = customActionModelRepository;
            _husbandryEnterpriseRepository = husbandryEnterpriseRepository;
            _husbandryEnterpriseImagesRepository = husbandryEnterpriseImagesRepository;
            _slaughterInformationRepository = slaughterInformationRepository;
            _slaughterImagesRepository = slaughterImagesRepository;
            _deepProcessingRepository = deepProcessingRepository;
            _deepProcessingImagesRepository = deepProcessingImagesRepository;
        }
        #region 养殖初始页面

        [HttpPost]
        public async Task<List<TraceabilityIndex>> GetTraceabilityIndexList()
        {
            var list = await _TraceabilityIndexRepository.GetAllAsync();
            return list;
        }
        [HttpPost]
        public async Task<int> AddTraceabilityIndex(TraceabilityIndex Traceabilityindex)
        {
            int index = 0;
            index = await _TraceabilityIndexRepository.InsertAsync(Traceabilityindex);
            return index;
        }

        public async Task<TraceabilityIndex> GetTraceabilityIndexById(int Id)
        {
            return await _TraceabilityIndexRepository.GetAsync(Id);
        }
        [HttpPost]

        public async Task<int> ModifyTraceabilityIndex(TraceabilityIndex Traceabilityindex)
        {
            int index = 0;
            index = await _TraceabilityIndexRepository.UpdateDataAsync(Traceabilityindex);
            return index;
        }
        [HttpGet]
        [AllowAnonymous]
        public async Task<int> DelTraceabilityIndexById(int Id)
        {
            int index;
            var model = await _TraceabilityIndexRepository.GetAsync(Id);
            index = await _TraceabilityIndexRepository.Delted(model);

            return index;
        }
        [HttpPost]
        [AllowAnonymous]
        public async Task<int> DelAllTraceabilityIndex(List<int> Ids)
        {
            int index = 0;
            var aa = await _TraceabilityIndexRepository.GetAllAsync1(d => Ids.Contains(d.IndexId));
            foreach (var item in aa)
            {
                index = await _TraceabilityIndexRepository.DeltedByid(item.IndexId);
            }

            return index;
        }
        //public object UploadFileSecond(IFormFile file)
        //{
        //    var filename = file.FileName;
        //    filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Path.GetExtension(filename);
        //    var path = Directory.GetCurrentDirectory() + @"\wwwroot\Images\" + filename;
        //    using (FileStream fs = new FileStream(path, FileMode.Create))
        //    {
        //        file.CopyTo(fs);

        //    }
        //    var url1 = "/Images/" + filename;
        //    return new {name= filename,url= url1 };

        //}

        [HttpPost]
        public async Task<int> ModifyPic(ModifyPicResult result)
        {
            var model = await _TraceabilityIndexRepository.GetAllAsync1(d => d.IndexId == result.iid);
            if (model.First().Imagess.Length == 0)
            {
                model.First().Imagess = result.pic;
            }
            else
            {
                model.First().Imagess += "," + result.pic;
            }

            int index = 0;
            index = await _TraceabilityIndexRepository.UpdateDataAsync(model.First());
            return index;
        }
        [HttpPost]
        public async Task<int> ModifyDelPic(ModifyPicResult result)
        {
            int index = 0;
            var model = await _TraceabilityIndexRepository.GetAllAsync1(d => d.IndexId == result.iid);
            var aa = model.First().Imagess.Split(",");
            var updatepaths = aa.Where(d => d.Trim() != result.pic).ToList();
            var newpath = string.Join(",", updatepaths);
            model.First().Imagess = newpath;
            index = await _TraceabilityIndexRepository.UpdateDataAsync(model.First());
            return index;
        } 
        #endregion

        [AllowAnonymous]
        public async Task<object> UploadFileSecond(IFormFile file)
        {
            //判断文件类型
            var extFilese = configuration["AllowFileExt"].Split('|');
            var fileExt = Path.GetExtension(file.FileName);
            if (!extFilese.Contains(fileExt))
            {
                throw new Exception("文件类型不正确");
            }
            //判断文件大小
            if (file.Length / 1024 > 100)
            {
                throw new Exception("文件太大了");
            }
            //存储位置和文件重命名
            var dirPath = $"/Images/{DateTime.Now.ToString("yyyy")}/{DateTime.Now.ToString("yyyyMMdd")}";
            if (!Directory.Exists($"{host.WebRootPath}{dirPath}")) ;
            {
                Directory.CreateDirectory($"{host.WebRootPath}{dirPath}");
            }
            Random random = new Random();
            var newFileName = $"{DateTime.Now.ToString("yyyyMMddHHmmssfff")}_{random.Next(100, 999)}{fileExt}";
            using (FileStream fs = new FileStream($"{host.WebRootPath}{dirPath}/{newFileName}", FileMode.Create))
            {
                await file.CopyToAsync(fs);
            }
            var path = $"{dirPath}/{newFileName}";
            return new { name = newFileName, url = path };
        }
        [HttpGet]
        public async Task<List<HusbandryMessage>> GetHusbandryMessagesAsync()
        {
            return await _HusbandryMessageRepository.GetAllAsync();
        }
        [HttpPost]
        public async Task<int> UpdateHusbandryMessagesAsync(HusbandryMessage mes)
        {
          return  await _HusbandryMessageRepository.UpdateDataAsync(mes);
        }
        [AllowAnonymous]
        [HttpGet]
        public async Task<string> GetTrace()
        {
          var model= await _TraceabilityIndexRepository.GetAllAsync();
            int count = model.Count();
            //创建一个新的QRCodeGenerator实例
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            //创建一个二维码 “123123”为显示内容
            QRCodeData qrCodeData = qrGenerator.CreateQrCode("https://blog.csdn.net/qq_40579788/article/details/115670373", QRCodeGenerator.ECCLevel.M, true);
            //放入生成的二维码
            QRCode qrCode = new QRCode(qrCodeData);
            //获取到二维码图形
            Bitmap qrCodeImage = qrCode.GetGraphic(15, Color.Black, Color.White, false);

            /* GetGraphic方法参数说明
             * public Bitmap GetGraphic(int pixelsPerModule, Color darkColor, Color lightColor, Bitmap icon = null, int iconSizePercent = 15, int iconBorderWidth = 6, bool drawQuietZones = true)
             * int pixelsPerModule:生成二维码图片的像素大小 ，我这里设置的是5 
             * Color darkColor：暗色   一般设置为Color.Black 黑色
             * Color lightColor:亮色   一般设置为Color.White  白色
             * Bitmap icon :二维码 水印图标 例如：Bitmap icon = new Bitmap(路径); 默认为NULL ，加上这个二维码中间会显示一个图标
             * int iconSizePercent： 水印图标的大小比例 ，可根据自己的喜好设置 
             * int iconBorderWidth： 水印图标的边框
             * bool drawQuietZones:静止区，位于二维码某一边的空白边界,用来阻止读者获取与正在浏览的二维码无关的信息 即是否绘画二维码的空白边框区域 默认为true
            */

            //新图形(给出自定义大小,可以解决二维码生成时因为内容而影响图片大小的问题)
            /*
             * 550为宽高 
             * +60为上下左右各留出30的空白区域
             * 35*2为我要给图片底下添加字体 最多两行 35是行高 提前调试得知
             */
            Bitmap newBM = new Bitmap(550 + 60, 550 + (35 * 2) + 60);
            //新画布
            Graphics newGP = Graphics.FromImage(newBM);
            //清除所有背景色并指定背景颜色
            newGP.Clear(Color.White);
            // 插值算法的质量
            newGP.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //将旧图画入新图中
            /*
             * qrCodeImage:旧图
             * new Rectangle(30, 30, 550, 550):在画布上操作的定位及宽高(前两个参数为距左边,距顶部,后边为宽高)  此处宽高为自定义
             * new Rectangle(0, 0, qrCodeImage.Width, qrCodeImage.Height):要操作图片的定位及宽高
             * GraphicsUnit.Pixel:使用像素为单位
             */
            newGP.DrawImage(qrCodeImage, new Rectangle(30, 30, 550, 550), new Rectangle(0, 0, qrCodeImage.Width, qrCodeImage.Height), GraphicsUnit.Pixel);
            //设置字体
            Font font = new Font("楷体", 30f, FontStyle.Bold, GraphicsUnit.Pixel);
            //文字居中(不会换行)
            //文字长度
            //int strWidth = (int)g2.MeasureString("嗷嗷待食发货时肯定会房间卡是放假卡上的合肥师范", font1).Width;
            //总长度减去文字长度的一半  （居中显示）
            //int wordStartX = (qrCodeImage.Width - strWidth) / 2;
            //int wordStartY = qrCodeImage.Height - 30;
            //g2.DrawString("嗷嗷待食发货时肯定会房间卡是放假卡上的合肥师范", font1, Brushes.Black, wordStartX, wordStartY);

            //以下为文字居中处理(可以换行)
            RectangleF rec = new RectangleF((float)(newBM.Width * 0.10), newBM.Height - ((35 * 2) + 15), (float)(newBM.Width * 0.80), font.Height * 2);
            Brush fontBrush = SystemBrushes.ControlText;
            //此处为设置居中方式可以让换行后的文字也居中
            StringFormat sformat = new StringFormat();
            sformat.Alignment = StringAlignment.Center;
            sformat.LineAlignment = StringAlignment.Center;
            newGP.DrawString("洋神金选诱惑黑丝眼镜大波浪", font, fontBrush, rec, sformat);
            //资源释放
            newGP.Dispose();
            //var aa = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            //string path = @"D:\专高六\项目\FarmingSystem01\Farming.WebApi\wwwroot\" + aa + ".jpg";
            var dirPath = $@"QRCoder\{DateTime.Now.ToString("yyyy")}\{DateTime.Now.ToString("yyyyMM")}\{DateTime.Now.ToString("yyyyMMdd")}";
            var fullDirPath = Path.Combine(host.WebRootPath, dirPath);
            if (!Directory.Exists(fullDirPath))
            {
                Directory.CreateDirectory (fullDirPath);
            }
            var newFileName = $"{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.jpg";
            var path = Path.Combine(fullDirPath, newFileName);

            newBM.Save(path);
            return $"{dirPath}/{newFileName}";
            
             
        }
        public async Task<List<HealthInformation>> GetHealthInformation()
        {
           return await _healthInformationRepository.GetAllAsync();
        }
        public async Task<int> AddHealthInformation(HealthInformation helth)
        {
            return await _healthInformationRepository.InsertAsync(helth);
        }
        public async Task<HealthInformation> GetHealthById(int Id)
        {
            return await _healthInformationRepository.GetAsync(Id);
        }
        [HttpPost]
        public async Task<int> UpdateHealthInformation(HealthInformation helth)
        {
            return await _healthInformationRepository.UpdateDataAsync(helth);
        }
        [HttpGet]
        public  async Task<List<CustomActionModel>> GetCustomActionModels()
        {
            return await _customActionModelRepository.GetAllAsync();
        }
        /// <summary>
        /// 获取企业信息
        /// </summary>
        /// <returns></returns>
        public async Task<List<HusbandryEnterprise>> GetHusbandryEnterprise()
        {
            return await _husbandryEnterpriseRepository.GetAllAsync();
        }
        /// <summary>
        /// 企业信息修改
        /// </summary>
        /// <param name="Enterprise"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> UpdateHusbandryEnterprise(HusbandryEnterprise Enterprise)
        {
            return await _husbandryEnterpriseRepository.UpdateDataAsync(Enterprise);
        }
       /// <summary>
       /// 获取动检证和企业照片集合
       /// </summary>
       /// <returns></returns>
        public async Task<List<HusbandryEnterpriseImages>> GetHusbandryEnterpriseImages()
        {
            return await _husbandryEnterpriseImagesRepository.GetAllAsync();
        }
        /// <summary>
        /// 动检证添加
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> ModifyHusbandryEnterpriseImages(ModifyPicResult result)
        {
            var model = await _husbandryEnterpriseImagesRepository.GetAllAsync1(d => d.EnterpriseImagesId == 1);
            if (model.First().DynamicVerification.Length == 0)
            {
                model.First().DynamicVerification = result.pic;
            }
            else
            {
                model.First().DynamicVerification += "," + result.pic;
            }

            int index = 0;
            index = await _husbandryEnterpriseImagesRepository.UpdateDataAsync(model.First());
            return index;
        }
        /// <summary>
        /// 动检证删除
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> ModifyDelHusbandryEnterpriseImages(ModifyPicResult result)
        {
            int index = 0;
            var model = await _husbandryEnterpriseImagesRepository.GetAllAsync1(d => d.EnterpriseImagesId == 1);
            var aa = model.First().DynamicVerification.Split(",");
            var updatepaths = aa.Where(d => d.Trim() != result.pic).ToList();
            var newpath = string.Join(",", updatepaths);
            model.First().DynamicVerification = newpath;
            index = await _husbandryEnterpriseImagesRepository.UpdateDataAsync(model.First());
            return index;
        }
        /// <summary>
        /// 企业照片添加
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> ModifyHusbandryEnterpriseCorporatePhotoImages(ModifyPicResult result)
        {
            var model = await _husbandryEnterpriseImagesRepository.GetAllAsync1(d => d.EnterpriseImagesId == 1);
            if (model.First().CorporatePhoto.Length == 0)
            {
                model.First().CorporatePhoto = result.pic;
            }
            else
            {
                model.First().CorporatePhoto += "," + result.pic;
            }

            int index = 0;
            index = await _husbandryEnterpriseImagesRepository.UpdateDataAsync(model.First());
            return index;
        }
        /// <summary>
        /// 企业照片删除
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> ModifyDelHusbandryEnterpriseCorporatePhotoImages(ModifyPicResult result)
        {
            int index = 0;
            var model = await _husbandryEnterpriseImagesRepository.GetAllAsync1(d => d.EnterpriseImagesId == 1);
            var aa = model.First().CorporatePhoto.Split(",");
            var updatepaths = aa.Where(d => d.Trim() != result.pic).ToList();
            var newpath = string.Join(",", updatepaths);
            model.First().CorporatePhoto = newpath;
            index = await _husbandryEnterpriseImagesRepository.UpdateDataAsync(model.First());
            return index;
        }
        /// <summary>
        /// 屠宰信息
        /// </summary>
        /// <returns></returns>
        public async Task<List<SlaughterInformation>> GetSlaughterInformation()
        {
            return await _slaughterInformationRepository.GetAllAsync();
        }
        /// <summary>
        /// 设置屠宰信息
        /// </summary>
        /// <param name="slaughter"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> UpdateSlaughterInformation(SlaughterInformation slaughter)
        {
            return await _slaughterInformationRepository.UpdateDataAsync(slaughter);
        }
        /// <summary>
        /// 查看相关资质和企业照片
        /// </summary>
        /// <returns></returns>
        public async Task<List<SlaughterImages>> GetSlaughterImages()
        {
            return await _slaughterImagesRepository.GetAllAsync();
        }
        /// <summary>
        /// 相关资质添加
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> AddRelevantQualificationSlaughterImages(ModifyPicResult result)
        {
            var model = await _slaughterImagesRepository.GetAllAsync1(d => d.SlaughterImagesId == 1);
            if (model.First().RelevantQualification.Length == 0)
            {
                model.First().RelevantQualification = result.pic;
            }
            else
            {
                model.First().RelevantQualification += "," + result.pic;
            }

            int index = 0;
            index = await _slaughterImagesRepository.UpdateDataAsync(model.First());
            return index;
        }
        /// <summary>
        ///相关资质删除
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> UpdateRelevantQualificationSlaughterImages(ModifyPicResult result)
        {
            int index = 0;
            var model = await _slaughterImagesRepository.GetAllAsync1(d => d.SlaughterImagesId == 1);
            var aa = model.First().RelevantQualification.Split(",");
            var updatepaths = aa.Where(d => d.Trim() != result.pic).ToList();
            var newpath = string.Join(",", updatepaths);
            model.First().RelevantQualification = newpath;
            index = await _slaughterImagesRepository.UpdateDataAsync(model.First());
            return index;
        }
        /// <summary>
        /// 屠宰企业照片添加
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> AddCorporatePhotoSlaughterImages(ModifyPicResult result)
        {
            var model = await _slaughterImagesRepository.GetAllAsync1(d => d.SlaughterImagesId == 1);
            if (model.First().CorporatePhoto.Length == 0)
            {
                model.First().CorporatePhoto = result.pic;
            }
            else
            {
                model.First().CorporatePhoto += "," + result.pic;
            }

            int index = 0;
            index = await _slaughterImagesRepository.UpdateDataAsync(model.First());
            return index;
        }
        /// <summary>
        /// 屠宰企业照片删除
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> UpdateCorporatePhotoSlaughterImages(ModifyPicResult result)
        {
            int index = 0;
            var model = await _slaughterImagesRepository.GetAllAsync1(d => d.SlaughterImagesId == 1);
            var aa = model.First().CorporatePhoto.Split(",");
            var updatepaths = aa.Where(d => d.Trim() != result.pic).ToList();
            var newpath = string.Join(",", updatepaths);
            model.First().CorporatePhoto = newpath;
            index = await _slaughterImagesRepository.UpdateDataAsync(model.First());
            return index;
        }
        /// <summary>
        /// 查询深加工信息
        /// </summary>
        /// <returns></returns>
        public async Task<List<DeepProcessing>> GetDeepProcessings()
        {
            return await _deepProcessingRepository.GetAllAsync();
        }

    }
}
